using Blog2025.Application.Common;
using Blog2025.Application.Dto;
using Blog2025.Domain.Entities.App;
using Blog2025.Domain.Filters;
using Blog2025.Domain.Repositories;

namespace Blog2025.Application.Services;
public class DepartmentAppServices : IDepartmentAppServices
{
    private readonly IRepository<AppDepartment> _DepartRep;
    private readonly IFilter<AppDepartment> _filter;
    public DepartmentAppServices(IRepository<AppDepartment> DepartRep,IFilter<AppDepartment> filter)
    {
        _DepartRep=DepartRep;
        _filter=filter;
    }
    public async Task CreateDepartmentAsync(CreateDepartmentDto dto)
    {
        var dep=new AppDepartment{DepartmentName=dto.DepartmentName};
        await _DepartRep.CreateAsync(dep);
    }

    public async Task DeleteDepartmentAsync(Guid id)
    {
        var dep=await _DepartRep.GetByIdAsync(id)?? throw new Exception("部门不存在");
        await _DepartRep.DeleteAsync(dep);
    }

    public async Task<dynamic> GelAllDepartmentAsync(PageRequestDto pageRequestDto)
    {
        var dep = await _DepartRep.GetPagedAsync(pageRequestDto.PageIndex,pageRequestDto.PageSize);
        int totalCount=dep.Count();
        int totalPage=(int)Math.Ceiling((double)dep.Count() / pageRequestDto.PageSize);
        int pageIndex=pageRequestDto.PageIndex;
        int pageSize=pageRequestDto.PageSize;
        var items=dep.Select(d=>new DepartmentDto{Id=d.Id,DepartmentName=d.DepartmentName});
        return PageResult.Success(totalCount,totalPage,pageIndex,pageSize,items);
    }
    // 过滤器
    public async Task<dynamic> GetFilterAsync(Dictionary<string ,object> filters)
    {
        var deps=await _DepartRep.GetAllAsync();
        return _filter.Filter(deps,filters);
    }

    public async Task<DepartmentDto> GelByIdDepartmentAsync(Guid id)
    {
        var dep=await _DepartRep.GetByIdAsync(id)?? throw new Exception("部门不存在");
        return new DepartmentDto{Id = dep.Id, DepartmentName = dep.DepartmentName};
    }

    public async Task UpdateDepartmentAsync(Guid id,string departmentName)
    {
        var dep=await _DepartRep.GetByIdAsync(id)?? throw new Exception("部门不存在");
        dep.DepartmentName=departmentName;
        await _DepartRep.UpdateAsync(dep);
    }
}